# Makefile for webook project
# 使用方法: make docker

# 变量定义
APP_NAME = webook
IMAGE_NAME = flycash/webook
CONTAINER_NAME = webook-test
# 使用立即赋值，确保在一次 make 执行过程中 VERSION 只计算一次，避免镜像标签与运行不一致
VERSION := $(shell date +%Y%m%d-%H%M%S)
PORT = 8081

# 默认目标
.PHONY: help
help:
	@echo "可用的命令:"
	@echo "  make build     - 构建Go二进制文件"
	@echo "  make image     - 构建Docker镜像"
	@echo "  make docker    - 完整部署流程 (构建+部署)"
	@echo "  make clean     - 清理构建文件"
	@echo "  make logs      - 查看容器日志"
	@echo "  make status    - 查看容器状态"
	@echo "  make stop      - 停止容器"
	@echo "  make restart   - 重启容器"

# 构建Go二进制文件
.PHONY: build
build:
	@echo "正在构建Go二进制文件..."
	CGO_ENABLED=0 GOOS=linux go build -a -installsuffix cgo -o $(APP_NAME) main.go
	@echo "构建完成: $(APP_NAME)"

# 构建Docker镜像
.PHONY: image
image: build
	@echo "正在构建Docker镜像..."
	docker build -t $(IMAGE_NAME):$(VERSION) .
	docker tag $(IMAGE_NAME):$(VERSION) $(IMAGE_NAME):latest
	@echo "镜像构建完成: $(IMAGE_NAME):$(VERSION)"

# 停止并删除旧容器
.PHONY: stop
stop:
	@echo "正在停止旧容器..."
	@docker stop $(CONTAINER_NAME) 2>/dev/null || true
	@docker rm $(CONTAINER_NAME) 2>/dev/null || true
	@echo "旧容器已清理"

# 启动新容器
.PHONY: start
start: stop
	@echo "正在启动新容器..."
	docker run -d --name $(CONTAINER_NAME) -p $(PORT):8080 $(IMAGE_NAME):$(VERSION)
	@echo "容器启动完成，等待服务就绪..."
	@sleep 3
	@echo "测试健康检查..."
	@curl -s http://localhost:$(PORT)/health > /dev/null && echo "✅ 部署成功！" || echo "❌ 部署失败，请检查日志"

# 完整部署流程
.PHONY: docker
docker: image start
	@echo ""
	@echo "🎉 项目部署完成！"
	@echo "📱 访问地址: http://localhost:$(PORT)"
	@echo "🔍 健康检查: http://localhost:$(PORT)/health"
	@echo "📊 查看状态: make status"
	@echo "📝 查看日志: make logs"

# 查看容器状态
.PHONY: status
status:
	@echo "容器状态:"
	@docker ps -a | grep $(CONTAINER_NAME) || echo "容器不存在"

# 查看容器日志
.PHONY: logs
logs:
	@echo "容器日志:"
	@docker logs $(CONTAINER_NAME) --tail 20

# 重启容器
.PHONY: restart
restart: stop start
	@echo "容器重启完成"

# 清理构建文件
.PHONY: clean
clean:
	@echo "正在清理构建文件..."
	@rm -f $(APP_NAME)
	@echo "清理完成"

# 清理所有Docker资源
.PHONY: clean-all
clean-all: clean
	@echo "正在清理Docker资源..."
	@docker stop $(CONTAINER_NAME) 2>/dev/null || true
	@docker rm $(CONTAINER_NAME) 2>/dev/null || true
	@docker rmi $(IMAGE_NAME):latest 2>/dev/null || true
	@echo "Docker资源清理完成"
